#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include "log.hpp"

enum
{
	SOCKERR = 1
};

void Usage(const std::string &proc)
{
	std::cout << "\r\nUsage: " << proc << "Serverport Serverip" << std::endl;
}

int main(int argc, char *argv[])
{
	// ./TcpServer Serverip Serverport
	if (argc != 3)
	{
		Usage(argv[0]);
		exit(0);
	}

	std::string Serverip = argv[1];
	uint16_t Serverport = std::stoi(argv[2]);

	int sockfd = 0;
	struct sockaddr_in Server;
	Server.sin_family = AF_INET;
	Server.sin_addr.s_addr = inet_addr(Serverip.c_str());
	Server.sin_port = htons(Serverport);
	socklen_t len = sizeof(Server);

	bool isreconnect = false;
	int cnt = 5;
	while (true)
	{
		sockfd = socket(AF_INET, SOCK_STREAM, 0);
		std::cout << sockfd << std::endl;
		if (sockfd < 0)
		{
			lg(FATAL, "socket create fail... sockfd: %d, errno: %d, strerror: %s\n", sockfd, errno, strerror(errno));
			exit(SOCKERR);
		}
		lg(INFO, "socket create success... sockfd: %d, errno: %d, strerror: %s\n", sockfd, errno, strerror(errno));

		do
		{
			// 连接
			int n = connect(sockfd, (struct sockaddr *)&Server, len);
			if (n > 0)
			{
				isreconnect = true;
				std::cout << "connect error... isreconnect: " << cnt-- << std::endl;
			}
			else
			{
				break;
			}
		} while (cnt && isreconnect);

		if (cnt == 0)
		{
			std::cerr << "user offline..." << std::endl;
			break;
		}

		while (true)
		{
			// 连接完成进行收发
			std::string message;
			std::cout << "plase Enter# ";
			// std::cout << message << std::endl;
			getline(std::cin, message);
			// std::cout << message << std::endl;

			ssize_t n = write(sockfd, message.c_str(), message.size());
			if (n <= 0)
			{
				std::cout << "write fail..." << std::endl;
			}
			// std::cout << "write success" << std::endl;
			// std::cout << "start read" << std::endl;
			char inbuffer[4096];
			n = read(sockfd, inbuffer, sizeof(inbuffer));
			if (n > 0)
			{
				inbuffer[n] = 0;
				// std::cout << "read success" << std::endl;
				std::cout << inbuffer << std::endl;
			}
			else
			{
				std::cout << "read fail..." << std::endl;
				break;
			}

			std::cout << "detail complete..." << std::endl;
			break;
		}
		break;
	}

	close(sockfd);
	return 0;
}
